#!/usr/bin/python2.4
#
# Copyright 2011 Google Inc. All Rights Reserved.

"""One-line documentation for electricity module.

A detailed description of electricity.
"""

__author__ = 'bst@google.com (Ben Stewart)'

RIVER = 'javascript:PopupRiver'
RIVERLABELS = ['Station No','River Height (m)','Time of Observation','Flood Class','Tendency','Minor (m)','Moderate (m)','Major (m)']
RIVERELEMENTS = ['name', 'station','lat', 'long','height',
                 'floodClass','tendency', 'time','minorHeight','moderateHeight','majorHeight']

from django.utils import simplejson, html
from controllers import geocode
import datetime
import logging
import urllib

def loadMaps():
  url = ('http://maps.google.com.au/maps/ms?hl=en&ie=UTF8&source=embed&' +
         'oe=UTF8&msa=0&msid=216570432711189139958.000499c1a23499b9afcb1&' +
         'output=kml')
  oldicons = ['http://maps.gstatic.com/intl/en_au/mapfiles/ms/micons/' +
              'blue-dot.png',
              'http://maps.gstatic.com/intl/en_ALL/mapfiles/ms/micons/' +
              'blue-dot.png']
  newicon = ('http://mapvisage.appspot.com/static/floodmap/images/rivers/' +
             'evaccentre.png')

  raw = urllib.urlopen(url)
  page = raw.read()

  for oldicon in oldicons:
    page = page.replace(oldicon, newicon)
  return page


def updateMap():
  from google.appengine.api import memcache
  # TODO(arb): also store in datastore
  memcache.set('vicevac', loadMaps())

def showMap():
  from google.appengine.api import memcache
  kml = memcache.get('vicevac')
  if kml is None:
    updateMap()
    kml = memcache.get('vicevac')

  return kml

from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app

class UpdatePage(webapp.RequestHandler):
  def get(self):
    updateMap()
    self.response.headers['Content-Type'] = 'text/plain'
    self.response.out.write('OK')

class ShowPage(webapp.RequestHandler):
  def get(self):
    self.response.headers['Content-Type'] = 'application/vnd.google-earth.kml+xml'
    now = datetime.datetime.utcnow()
    expires = now + datetime.timedelta(minutes=5)
    self.response.headers['Expires'] = (
        expires.strftime('%a, %d %b %Y %H:%M:%S GMT'))
    self.response.headers['Cache-Control'] = 'public, max_age=300'
    self.response.out.write(showMap())

application = webapp.WSGIApplication([('/kml/vicevac/update__', UpdatePage),
                                      ('/kml/vicevac', ShowPage)], debug=True)

def main():
  run_wsgi_app(application)

if __name__ == "__main__":
  main()
